// 方式五
// 时间：200ms
function longestPalindrome(s) {
  const len = s.length;
  if (len < 2) return s;
  let maxLenStr = "";
  for (let n = 0; n < len; n++) {
    const [start, end] = getPos(s, n);
    let palindromeStr = s.substring(start, end + 1);
    if (palindromeStr.length > maxLenStr.length) {
      maxLenStr = palindromeStr;
    }
    const [startMid, endMid] = getPosMiddle(s, n + 0.5);
    let palindromeMidStr = s.substring(Math.ceil(startMid), Math.ceil(endMid));
    if (palindromeMidStr.length > maxLenStr.length) {
      maxLenStr = palindromeMidStr;
    }
  }
  return maxLenStr;

  function getPos(string, index) {
    let start = index;
    let end = index;
    while (
      start > 0 &&
      end < string.length &&
      string.substr(start - 1, 1) === string.substr(end + 1, 1)
    ) {
      start--;
      end++;
    }
    return [start, end];
  }
  function getPosMiddle(string, mid) {
    let start = mid;
    let end = mid;
    while (
      start > -0.5 &&
      end < string.length - 0.5 &&
      string.substr(Math.ceil(start - 1), 1) ===
        string.substr(Math.floor(end + 1), 1)
    ) {
      start--;
      end++;
    }
    return [start, end];
  }
}

console.log(
  longestPalindrome(
    "1234567890987654321123456789098765432112345678909876543211234567890987654321123456789098765432112345678909876543211234567890987654321123456789098765432112345678909876543211234567890987654321123456789098765432112345678909876543211234567890987654321"
  )
);
